#include "gui.h"

GUI::GUI(QWidget *parent)
	: QMainWindow(parent){
	ui.setupUi(this);
	

	QPalette* palette = new QPalette();	
 	palette->setBrush(QPalette::Background,*(new QBrush(*(new QPixmap(":/GUI/Resources/Background Image.jpg")))));
 	setPalette(*palette); 


	//if(BotControl->checkCommand(input))
	

	//Setting up suggestions of words for QCompleter for command line input
	createGlobalShortcut();
	createSystemTrayIcon();
	trayIcon->show();

	//Set up clock
	timer = new QTimer (this);
	timer ->start();
	


	//Set up Help Box
	_isHelpDisplayed = false;
	ui.HelpTopics->setGeometry(0,0,0,0);
	//ui.HelpTopics->setGeometry(0, -271, 231, 271));

	ui.commandInput->setPlaceholderText("Enter Commands");

    tickLabel = new QPixmap(":/GUI/Resources/tick.png");
	crossLabel = new QPixmap(":/GUI/Resources/cross.png");

	
	BotControl = Bot::getInstance();

	initRemindersForToday();

	//I need a function to count the number of tasks due today, and number of events that is happening today to put into this Message
	trayIcon->showMessage("Reminders", "You have " +  thingsToday + " things today!", QSystemTrayIcon::Information);	


	model = NULL;

	//Set up data by reading the .txt file upon first load of program
	
    setupModel();

	//Suggestions based on add Delete etc...
	/*
	QStringList stringList;
	stringList << "add" << "delete" << "display" << "displayw" << "search";
	//comp = new QCompleter(stringList, this);
	//comp = new QCompleter(this);
	//comp->setModel(modelFromFile(":/GUI/Resources/wordlist.txt")); 
	//This sets to a list of all possible words. However, it doesnt work in the sense that it will just check the entire line as a string not individual words
	//Need to custom the lineEdit class I think
	*/

	//Suggestions based on model column 0 data

	

	setUpConnections();
	setStyles();
	setHelp();
	setLabel();
	/*QString testStr;
	testStr = "<h3><u>Today";
	int width = ui.textEdit->width();
	testStr += "&nbsp;&nbsp;&nbsp;";
	testStr += QDate::currentDate().toString("ddd MMMM d");
	testStr += "</h3>";
	
	QString testStr5 = "<table width = \"100%\"><tr><td align = \"left\"><span style=\" font-size:15pt; font-weight:600;\">Today</td></span><td align = \"right\"><span style=\" font-size:10pt; color:grey;\">13th March</td></span></tr></table><br><br>";
	
	ui.textEdit->setHtml(testStr5);




	QString testStr3= "<table width = \"400\"; border = \"1px\">";
	testStr3 += "<td width = \"400\"; float=\"right\">Left-aligned</td>";
	testStr3 += "<td float= \"left\">Right-Aligned</td></table>";
//	ui.textBrowser->setHtml(testStr3);

	//works only for tables!
	QString testStr2 = "<span class=\"left\">Text on the right</span> <span class=\"right\">Text on the left</span>";
	//ui.textEdit->setHtml(testStr2);

	QString testStr4 = "<p><span style=\" font-size:10pt; font-weight:600; color:red;\">1. Task Name</span><br><span style=\" font-size:8pt; color:red;\">3:00pm - 4:30pm</span></p>";
	testStr4 += "<p><span style=\" font-size:10pt; font-weight:600;\">2. Task Name</span><br><span style=\" font-size:8pt; color:grey;\">9:00am - 12:00pm</span></p>";
	ui.textEdit->append(testStr4); 
	*/

	/*
	vector<vector<CommonUtils::ReturnString>> outputVector;

	vector<CommonUtils::ReturnString> section1Vector;
	pair<string,string> header("Today", "21 Mar");
	CommonUtils::ReturnString header1;
	header1.entry = header;
	header1.format = 0;

	pair<string,string> data("Task 1", "By 9am");
	CommonUtils::ReturnString data1;
	data1.entry = data;
	data1.format = 0;

	pair<string,string> data2("Event 1", "9:00 am to 12:00pm");
	CommonUtils::ReturnString _data2;
	_data2.entry = data2;
	_data2.format = 0;

	section1Vector.push_back(header1);
	section1Vector.push_back(data1);
	section1Vector.push_back(_data2);

	outputVector.push_back(section1Vector);
	*/
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY);
	OutputManager converter(output.displayMsg);
	QString outputStr = converter.getFormattedString();
	ui.textEdit->setHtml(outputStr);
	ui.statusBar->showMessage(QString::fromStdString(output.statusMsg));


	//Set up label for valid command check
	QPixmap crossLabel(":/GUI/Resources/cross.png");

	int w = ui.validInputLabel->width();
	int h = ui.validInputLabel->height();

	//if(BotControl->checkCommand(input))
	
	ui.validInputLabel-> setPixmap(crossLabel.scaled(w,h,Qt::KeepAspectRatio));

	QPixmap helpLabel(":/GUI/Resources/cross.png"); //REPLACE THIS FOR HELP WITH WHAT THE COLOR MEANS

	int w1 = ui.ColorMeaningLabel->width();
	int h1 = ui.ColorMeaningLabel->height();

	//if(BotControl->checkCommand(input))
	

	//setAttribute(Qt::WA_TranslucentBackground);
	QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect();
	effect->setBlurRadius(5);
	ui.textEdit->setGraphicsEffect(effect);
	ui.textEdit->setReadOnly(true);
	
	ui.ColorMeaningLabel-> setPixmap(helpLabel.scaled(w1,h1,Qt::KeepAspectRatio));
	//Implementation of Windows Flag to Customize appearances
	//setWindowFlags(Qt::Widget | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); //remove menu bar
	//setWindowFlags(Qt::Window| Qt::WindowMinimizeButtonHint| Qt::WindowCloseButtonHint); //DIsable maximize
	//setWindowFlags(Qt::Window| Qt::WindowCloseButtonHint| Qt::WindowContextHelpButtonHint); //Not possible to have minimize though

	//Set Up Shortcut Keys
	new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z), this, SLOT(undoCalled()));
	new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Y), this, SLOT(redoCalled()));
	//new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_A), this, SLOT(show()));

	//ui.textEdit->resize(ui.textEdit->document()->size().width(),ui.textEdit->document()->size().height() + 10);

}
void GUI::setLabel() {
	CommonUtils::ReturnCount entryCount = BotControl->getCount();

	if(QString::number(entryCount.numOverdue) == "0"){
		ui.label_2->hide();
	}else{
		ui.label_2->show();
		ui.label_2->setText(QString::number(entryCount.numOverdue));
	}
	if(QString::number(entryCount.numToday) == "0"){
		ui.label_3->hide();
	}else{
		ui.label_3->show();
		ui.label_3->setText(QString::number(entryCount.numToday));
	}
	if(QString::number(entryCount.numEvents+entryCount.numTasks) == "0"){
		ui.label_4->hide();
	}else{
		ui.label_4->show();
		ui.label_4->setText(QString::number(entryCount.numEvents+entryCount.numTasks));
	}
	if(QString::number(entryCount.numEvents) == "0"){
		ui.eventsLabel->hide();
	}else{
		ui.eventsLabel->show();
		ui.eventsLabel->setText(QString::number(entryCount.numEvents));
	}
	if(QString::number(entryCount.numTasks) == "0"){
		ui.tasksLabel->hide();
	}else{
		ui.tasksLabel->show();
		ui.tasksLabel->setText(QString::number(entryCount.numTasks));
	}

}

void GUI::initRemindersForToday(){
	CommonUtils::ReturnCount entryCount = BotControl->getCount();
	thingsToday = QString::number(entryCount.numToday);
	thingsOverdue = QString::number(entryCount.numOverdue);
}

//Make model out of ponter to vector
void GUI::setupModel()
{
	//vector<Entry*> vect= (BotControl->allEntries.getActive());
	//int size = vect->size();
	if(model !=NULL){
		delete model;
	}
	model = new Model(this,BotControl);
	assert (model != NULL);
	ui.tableView->setModel(model);
	ui.tableView->setShowGrid(false);
	//Prevent selection of all items by clicking button at NW Corner
	ui.tableView->setCornerButtonEnabled (false);
	//ui.tableView->setStyleSheet("QTableCornerButton::section {    background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);color: white;padding-left: 4px;border: 1px solid #6c6c6c;}"); 
	//Stretch the last column to fit
	ui.tableView->horizontalHeader()->setStretchLastSection(true);
	/*
	//Sorting by the respective header enabled
	QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
	proxyModel->setSourceModel( model );
    ui.tableView->setModel( proxyModel ); 
	ui.tableView->setSortingEnabled(true);*/
	comp = new QCompleter(this);
	comp->setModel(model);
	comp->setCompletionRole(Qt::DisplayRole);
	comp->setCompletionColumn(0);
	comp->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
	comp->setCaseSensitivity(Qt::CaseInsensitive);
	ui.commandInput->setCompleter(comp);
}


GUI::~GUI(){

	delete BotControl;
}


void GUI::setUpConnections(){


	//connect clock
	connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
	//Connect the tabBar buttons to what should be filtered
	connect(ui.EntriesDisplay, SIGNAL(currentChanged(int)), this, SLOT(receiveDisplayInstructions()));
	
	//Connect Calendars, double clicked = activated, clicked = show what is happening on that day
	connect(ui.Calendar,SIGNAL(activated(const QDate&)), this, SLOT(receiveCalendarCmd()));
	connect(ui.Calendar,SIGNAL(clicked(const QDate&)), this, SLOT(displayCalendarDate(const QDate&)));
	
	/* Connect Change of Dates
	connect(BotControl, SIGNAL(addTasksOrEvents(const QDate&)), ui.Calendar, SLOT(receiveCalendarEntryExists(const QDate&));
	connect(BotControl, SIGNAL(delTasksOrEvents(const QDate&)), ui.Calendar, SLOT(receiveCalendarEntryExists(const QDate&));
	*/

	//Connect command inputs stuff
	//1. Receive command upon pressing enter
	//2. Display the help text based on the first char user enters, upon text edited
	//3. Undo from pressing CTRL-Z in command line
	//4. Redo from pressing CTRL-Y in command line
	//5. Either Tick or Cross
	//6. Color the respective keywords, add, from to, delete etc...
	/*connect(ui.commandInput, SIGNAL(returnPressed()), this, SLOT(receiveCommand()));
	connect(ui.commandInput, SIGNAL(textEdited(const QString&)), this, SLOT(displayHelpInput(const QString&)));
	connect(ui.commandInput, SIGNAL(undoShortcutPressed()), this, SLOT(undoFromCommandInput()));
	connect(ui.commandInput, SIGNAL(redoShortcutPressed()), this, SLOT(redoFromCommandInput()));
	connect(ui.commandInput, SIGNAL(textEdited(const QString&)), this, SLOT(validCommandInput(const QString&)));
	*/
	
	connect(ui.commandInput, SIGNAL(enterKeyPressed()), this, SLOT(receiveCommand()));
	//connect(ui.commandInput, SIGNAL(enterKeyPressed()), ui.commandInput, SLOT(clear()));
	connect(ui.commandInput, SIGNAL(textChanged()), this, SLOT(displayHelpInput()));
	connect(ui.commandInput, SIGNAL(textChanged()), this, SLOT(validCommandInput()));
	connect(ui.commandInput, SIGNAL(undoShortcutPressed()), this, SLOT(undoFromCommandInput()));
	connect(ui.commandInput, SIGNAL(redoShortcutPressed()), this, SLOT(redoFromCommandInput()));

	//These 2 connections are lagging the qlineEdit need a better algorithm!!!
	
	//Connect KeyPressEvent for Shortcuts
	//1. Ctrl-Z anywhere in the GUI except for the command line, linked to undo
	connect(this, SIGNAL(keyPressEvent(const QKeyEvent *e)), this, SLOT(undoFromCommandInput(const QKeyEvent *e)));

	connect(ui.eventsButton, SIGNAL(pressed()), this, SLOT(filterEventsfromClick()));
	connect(ui.tasksButton, SIGNAL(pressed()), this, SLOT(filterTasksfromClick()));
	connect(ui.allButton, SIGNAL(pressed()), this, SLOT(filterAllfromClick()));

}

//Set Style Sheet, Mostly for Calendar
void GUI::setStyles(){

/*QString style=/*"QMenu { font-size:16px; width: 150px; left: 20px;"
"background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 #cccccc, stop: 1 #333333);}"
"QToolButton {icon-size: 48px, 48px;background-color: qlineargradient(x1:0, y1:0, x2:0,"
"y2:1, stop: 0 #cccccc, stop: 1 #333333);"
"height: 100px; width: 200px;}"
"QAbstractItemView {selection-background-color: rgb(255, 174, 0);}"
"QToolButton::menu-arrow {}"
"QToolButton::menu-button {}"
"QToolButton::menu-indicator{width: 50px;}"
"QToolButton::menu-indicator:pressed,"
"QToolButton::menu-indicator:open{top:10px; left: 10px;}"
"QListView {background-color:white;}"
"QSpinBox::up-button { subcontrol-origin: border;"
"subcontrol-position: top right; width:50px; border-image: url(icons:arrow_up_n.png);}"
"QSpinBox::down-button {subcontrol-origin: border; subcontrol-position: bottom right;"
"border-width: 1px; width:50px;}"
"QSpinBox::down-arrow { width:26px; height:17px;"
"image: url(icons:arrow_down_n.png); } ";
ui.Calendar->setStyleSheet(style);*/

//Change color of nav Bar
/*	
QWidget *calendarNavBar = ui.Calendar->findChild<QWidget *>("qt_calendar_navigationbar");
if (calendarNavBar) {
	QPalette pal = calendarNavBar->palette();
	pal.setColor(calendarNavBar->backgroundRole(), QColor(220, 231, 245));
	pal.setColor(calendarNavBar->foregroundRole(), QColor(21, 28, 85));
	calendarNavBar->setPalette(pal);
	//ui.Calendar->setStyleSheet("background-color: red");
*/

//NOT WORKING AS IT SHOULD BE?
/*
ui.Calendar->setStyleSheet( "QDateEdit {"
"min-height:"+QString::number(10)+"px; "
"max-height:"+QString::number(10)+"px; "
"min-width:"+QString::number(10)+"px; "
"margin: 0px; padding-top: 0x; padding-bottom: 0px; "
"color: rgb(90,31,0); background-color: rgb(253, 231, 146);"
"}"
"QDateEdit::up-button { subcontrol-position: right; height: "+QString::number(10)+"px; width: "+QString::number(10)+"px; subcontrol-color: rgb(90,31,0);}"
"QDateEdit::drop-down { subcontrol-position: right; height: "+QString::number(10)+"px; width: "+QString::number(10)+"px; background-color: rgb(253, 231, 146);}"
"QDateEdit::up-button { width: "+QString::number(10000)+"px; height: "+QString::number(10)+"px; background-color: rgb(253, 231, 146); }"
"QDateEdit::up-arrow { "
"border-left: "+10+"px solid none;"
"border-right: "+10+"px solid none;"
"border-bottom: "+10+"px solid rgb(90,31,0);"
"width: 0px; height: 0px; }"
"QDateEdit::drop-down { width: "+QString::number(10)+"px; height: "+QString::number(10)+"px; background-color: rgb(253, 231, 146); }"
"QDateEdit::down-arrow { "
"border-left: "+10+"px solid none;"
"border-right: "+10+"px solid none;"
"border-top: "+10+"px solid rgb(90,31,0);"
"width: 0px; height: 0px; }"
"#qt_calendar_prevmonth {width: "+QString::number(10)+"px; height: "+QString::number(10)+"px; icon-size: "+QString::number(10)+"px}"
"#qt_calendar_nextmonth {width: "+QString::number(10)+"px; height: "+QString::number(10)+"px; icon-size: "+QString::number(10)+"px}"

"margin-bottom: 0px; border-width: 0px; padding: 0px;"
"min-height:"+QString::number(10)+"px; "
"border: 0px solid rgb(90,31,0);"
"color: rgb(90,31,0);"

);*/

	//ui.Calendar -> setPalette(QPalette(Qt::white)); 
	//ui.Calendar->setStyleSheet("background-color: white");
	//Color cant set properly

	//Color Today's date
	QTextCharFormat currentDayHighlight;
	currentDayHighlight.setBackground(Qt::cyan);
	QDate today = QDate::currentDate();
	ui.Calendar->setDateTextFormat(today, currentDayHighlight);




}

//Set tooltips for functions
void GUI::setHelp(){
	ui.commandInput->setWhatsThis("Enter in the following format [Command][Description][At/By][Date and Time]");
	ui.Calendar->setToolTip("Double Click on a date to enter entry, dates in red have a event/task");
	ui.EntriesDisplay->setToolTip("All your tasks for these 7 days");
}

void GUI::receiveCommand(){
	
	//std::string userCmd = ui.commandInput->text().toStdString();
	std::string userCmd = ui.commandInput->toPlainText().toStdString();
	ui.commandInput->setText("");

	CommonUtils::ReturnStatus output;
	
	if(userCmd == "help" && !_isHelpDisplayed){

		//Animation for Entering
		QPropertyAnimation *animation = new QPropertyAnimation(ui.HelpTopics, "geometry");
		animation->setDuration(100);
		//animation->setStartValue(QRect(-271, 0, 231, 271));
		//animation->setEndValue(QRect(0, 0, 231, 271));
		animation->setStartValue(QRect(29, 33, 0, 0));
		animation->setEndValue(QRect(29, 33, 219, 276));
		animation->start();
		_isHelpDisplayed = true;
	}else if(_isHelpDisplayed){

		//Animation for exiting help upon new cmd entered
		QPropertyAnimation *animation = new QPropertyAnimation(ui.HelpTopics, "geometry");
		animation->setDuration(100);
		//animation->setStartValue(QRect(0, 0, 231, 271));
		//animation->setEndValue(QRect(-271, 0, 231, 271));
		animation->setStartValue(QRect(29, 33, 219, 276));
		animation->setEndValue(QRect(29, 33, 0, 0));
		animation->start();
		output = BotControl->executeCommand(userCmd);
		_isHelpDisplayed = false;

		output = BotControl->executeCommand(userCmd);
		OutputManager converter(output.displayMsg);
		QString outputStr = converter.getFormattedString();
		ui.textEdit->setHtml(outputStr);
		setupModel();
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage));
		setLabel();
	}else{ //no help is displayed, help not input as cmd
		output = BotControl->executeCommand(userCmd);
		OutputManager converter(output.displayMsg);
		QString outputStr = converter.getFormattedString();
		if(outputStr != "")
			ui.textEdit->setHtml(outputStr);
		setupModel();
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage));
		setLabel();
	}
	//If we are using TextEdit
	//ui.commandInput->setPlainText("");
}

void GUI::receiveDisplayInstructions(){

	if(ui.EntriesDisplay->currentIndex() == 0){
		CommonUtils::ReturnStatus output = BotControl->getDefaultView();
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}

	if(ui.EntriesDisplay->currentIndex() == 1){
		BotControl->getDefaultView();
		CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_EVENT);
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}
	if(ui.EntriesDisplay->currentIndex() == 2){
		BotControl->getDefaultView();
		CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_TASK);
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}
	setupModel();
}

void GUI::receiveCalendarCmd(){
	//Make a new class for this dialog for entering dates!	
	QMessageBox::information(this,"Add Entry", "Enter Date" , QMessageBox:: Ok | QMessageBox:: Cancel);
}

void GUI::receiveCalendarEntryExists(const QDate& receivedDate){

	//all adding of events/tasks will emit that the day should be colored
	QTextCharFormat updateTextFormat;
	updateTextFormat.setForeground(Qt::green);
	ui.Calendar->setDateTextFormat(receivedDate, updateTextFormat);
	//all deleteing of events/tasks will emit that the day should not be colored
}

//Slot for changing textLabel
void GUI::displayHelpInput(const QString& inputStr)
{
	if(inputStr == "a")
		ui.label->setText("add <date> ....");
	if(inputStr == "d")
		ui.label->setText("delete <lineNumber>");
	if(inputStr == "image")
	{
		QPixmap pixmap(":/GUI/Resources/Splash Screen.jpg");
		ui.label->setPixmap(pixmap);
	}
}

void GUI::displayHelpInput()
{
	QString inputStr;
	inputStr = ui.commandInput->toPlainText();

	if(inputStr == "a")
		ui.label->setText("add <date> ....");
	if(inputStr == "d")
		ui.label->setText("delete <lineNumber>");
	if(inputStr == "image")
	{
		QPixmap pixmap(":/GUI/Resources/Splash Screen.jpg");
		ui.label->setPixmap(pixmap);
	}
}

void GUI::validCommandInput(const QString &input)
{

	int w = ui.validInputLabel->width();
	int h = ui.validInputLabel->height();

	//if(BotControl->checkCommand(input))
	
	ui.validInputLabel-> setPixmap(crossLabel->scaled(w,h,Qt::KeepAspectRatio));
	QRegExp rx("(Mon(?:day)?|Tue(?:sday)?|Wed(?:nesday)?|Thu(?:r(?:s(?:day)?)?)?|Fri(?:day)?|Sat(?:urday)?|Sun(?:day)?)");
	if(rx.indexIn(input) != -1)
	{
		ui.validInputLabel->setPixmap(tickLabel->scaled(w,h,Qt::KeepAspectRatio));
	}
}

void GUI::validCommandInput()
{


	int w = ui.validInputLabel->width();
	int h = ui.validInputLabel->height();

	//if(BotControl->checkCommand(input))
	QRegExp rx("(Mon(?:day)?|Tue(?:sday)?|Wed(?:nesday)?|Thu(?:r(?:s(?:day)?)?)?|Fri(?:day)?|Sat(?:urday)?|Sun(?:day)?)", Qt::CaseInsensitive);
	ui.validInputLabel-> setPixmap(crossLabel->scaled(w,h,Qt::KeepAspectRatio));

	if(rx.exactMatch(ui.commandInput->toPlainText()) == true)// "lala")
	{
		ui.validInputLabel->setPixmap(tickLabel->scaled(w,h,Qt::KeepAspectRatio));
	}
}


//This function is for QCompleter, to read data from .qrc file
QAbstractItemModel *GUI::modelFromFile(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly))
        return new QStringListModel(comp);

#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#endif
    QStringList words;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        if (!line.isEmpty())
            words << line.trimmed();
    }

#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif
    return new QStringListModel(words, comp);
}

void GUI::undoCalled(){

	//The shortcut doesnt work if the focus is on the lineEdit, because lineEdit takes that in as well!
	//setWindowTitle("UNDO SUCCESS");
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_UNDO);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
}

void GUI::undoFromCommandInput(){
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_UNDO);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
}

void GUI::undoFromCommandInput(QKeyEvent *e){
	
	bool isUndoShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Z); //Ctrl + Z
		if(isUndoShortcut)
		{
			CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_UNDO);
				setupModel();
			std::string statusMessage = output.statusMsg;
			statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
		}
}

void GUI::redoCalled(){

	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_REDO);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
}

void GUI::redoFromCommandInput(){
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_REDO);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
}


void GUI::displayCalendarDate(const QDate& dateClicked){
	
	QString input = "search " + dateClicked.toString(CommonUtils::FORMAT_DATE);
	string inputstr = input.toStdString();

	if(ui.EntriesDisplay->currentIndex() == 0){
		BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY);
		CommonUtils::ReturnStatus output = BotControl->executeCommand(inputstr);
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}

	if(ui.EntriesDisplay->currentIndex() == 1){
		BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY);
		BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_EVENT);
		CommonUtils::ReturnStatus output = BotControl->executeCommand(inputstr);
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}
	if(ui.EntriesDisplay->currentIndex() == 2){
		BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY);
		BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_TASK);
		CommonUtils::ReturnStatus output = BotControl->executeCommand(inputstr);
		std::string statusMessage = output.statusMsg;
		statusBar()->showMessage(QString::fromStdString(statusMessage),1000);
	}
	setupModel();
}

void GUI::createSystemTrayIcon()
{
	QAction* show = new QAction("Show", this);
	connect(show, SIGNAL(triggered()), this, SLOT(showNormal()));

	QAction* close = new QAction("Close", this);
	connect(close, SIGNAL(triggered()), this , SLOT(quitCmd()));

	QMenu* trayIconMenu = new QMenu(this);

	trayIconMenu->addAction(show);
	trayIconMenu->addSeparator();
	trayIconMenu->addAction(close);

	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setContextMenu(trayIconMenu);
	trayIcon->setIcon(QIcon(":/GUI/Resources/Splash Screen.jpg"));

	connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClicked(QSystemTrayIcon::ActivationReason)));

}

void GUI::trayIconClicked(QSystemTrayIcon::ActivationReason reason){
	if(reason == QSystemTrayIcon::Trigger){
		this->show();
	}
}

void GUI::quitCmd()
{
	//qApp->quit();
	exit(0); //Feels like a stop gap solution. qApp->quit() is crashing the program , ask Javier
}

void GUI::createGlobalShortcut(){
	shortcut = new QxtGlobalShortcut(this);
	connect(shortcut, SIGNAL(activated()), this, SLOT(toggleVisibility()));
	shortcut->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Space));
}

void GUI::toggleVisibility(){	
	if(this->isVisible()){		
		this->hide();
	}
	else{
		this->showNormal(); //Why is it appearing so quickly with a white flash!??
	}
}

void GUI::showTime(){

	QTime time = QTime::currentTime();

	QString time_text = time.toString("hh:mm ap");
	/*
	if(time.second() % 2 == 0)
	{
		time_text[1] = ' ';
	}*/
	ui.DigitalTime->setText(time_text);

	
	QDate currentDate = QDate::currentDate();
	QString dateText = currentDate.toString("ddd, MMMM d");
	ui.DigitalDate->setText(dateText);

}

void GUI::filterAllfromClick(){
	CommonUtils::ReturnStatus output = BotControl->getDefaultView();
	OutputManager converter(output.displayMsg);
	QString outputStr = converter.getFormattedString();
	ui.textEdit->setHtml(outputStr);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage));
}

void GUI::filterEventsfromClick(){
	BotControl->getDefaultView();
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_EVENT);
	OutputManager converter(output.displayMsg);
	QString outputStr = converter.getFormattedString();
	ui.textEdit->setHtml(outputStr);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage));
}

void GUI::filterTasksfromClick(){
	BotControl->getDefaultView();
	CommonUtils::ReturnStatus output = BotControl->executeCommand(CommonUtils::STRING_COMMAND_DISPLAY_TASK);
	OutputManager converter(output.displayMsg);
	QString outputStr = converter.getFormattedString();
	ui.textEdit->setHtml(outputStr);
	setupModel();
	std::string statusMessage = output.statusMsg;
	statusBar()->showMessage(QString::fromStdString(statusMessage));
}
